import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:lcapp/api/interface/user_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/jy_address_entity.dart';
import 'package:lcapp/model/refresh/refresh.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/page/aMapView/amap_tool.dart';
import 'package:lcapp/page/home/home_sel_address.dart';
import 'package:lcapp/widget/asr_app_bar.dart';

class MinAddAddressPage extends StatefulWidget {
  final Map arguments;
  const MinAddAddressPage({Key? key, required this.arguments}) : super(key: key);

  @override
  State<MinAddAddressPage> createState() => _MinAddAddressPageState();
}

class _MinAddAddressPageState extends State<MinAddAddressPage> {

  JyAddressEntity entity=JyAddressEntity();
  TextEditingController _controller = TextEditingController();
  FocusNode _focusNode = FocusNode();
  List searchAddressList = [];
  int page = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _focusNode.addListener(focusLisitener);
    if(widget.arguments!=null){
      entity = JyAddressEntity().fromJson(widget.arguments['address']);
      _controller.text = entity.detailAddress!;
    }
  }

  focusLisitener(){
    if(_focusNode.hasFocus){
      if(entity.province==null||entity.province!.isEmpty){
        _controller.text = '';
        showToast('请选择所在地区~');
      }
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AsrAppBar(
        title: Text(entity.id!=null?'编辑地址':'新增地址'),
        backgroundColor: defaultBarColor,
        barColor: Colors.white,
        actions: [
          Visibility(child: GestureDetector(
              onTap: ()async{
                FocusScope.of(context).requestFocus(FocusNode());
                ResponseData res = await UserAPI.deleteMyJYaddress(entity.id!);
                if(res.code==200){
                  showToast('删除成功');
                  Navigator.of(context).pop();
                }
              },
              child: Container(
                width: 100.w,
                alignment: Alignment.centerRight,
                padding: EdgeInsets.only(right: 30.w),
                child: Icon(Icons.delete,size: 45.sp,color: Colors.white,),
              )
          ),visible: entity.id!=null,)
        ],
      ),
      body: GestureDetector(
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          child: Column(
            children: [
              Expanded(child: Container(
                padding: EdgeInsets.only(left: 30.w),
                child: Column(
                  children: [
                    Container(
                      height: 120.w,
                      child: Column(
                        children: [
                          Expanded(child: Container(
                            padding: EdgeInsets.only(right: 30.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Text('所在地区',style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 32.sp,
                                ),),
                                Expanded(child: GestureDetector(
                                  onTap: (){
                                    FocusScope.of(context).requestFocus(FocusNode());
                                    SmartDialog.show(
                                      alignment: Alignment.bottomCenter,
                                      clickMaskDismiss: true,
                                      maskColor: Color.fromRGBO(0, 0, 0, 0.5), builder: (BuildContext context) {
                                        return HomeSelAddressPage(selAddress: (proName,cityName,name,code,){
                                          setState(() {
                                            entity.detailAddress = '$proName $cityName $name';
                                            if(entity.adCode==null||entity.adCode!=code){
                                              entity.detailAddress = '';
                                              _controller.text = entity.detailAddress!;
                                              searchAddressList = [];
                                              page = 1;
                                            }
                                            entity.adCode = code;
                                            entity.province = proName;
                                            entity.city = cityName;
                                            entity.region = name;
                                          });
                                        },);
                                    },
                                    );
                                  },
                                  child: Container(
                                    margin: EdgeInsets.only(left: 20.w,right: 6.w),
                                    child: Text(entity.province==null?'请选择所在地区':'${entity.province} ${entity.city} ${entity.region}',
                                      textAlign: TextAlign.right,
                                      style: TextStyle(
                                        color: entity.province==null||entity.province!.isEmpty?Color(0xff999999): Colors.black,
                                        fontSize: 28.sp,
                                      ),),
                                  ),
                                )),
                                Icon(Icons.arrow_forward_ios,color: Colors.black,size: 30.w,)
                              ],
                            ),
                          )),
                          Container(
                            height: 0.5,
                            color: Color(0xffE9E8E9),
                          )
                        ],
                      ),
                    ),
                    Container(
                      height: 250.w,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Expanded(child: Container(
                            padding: EdgeInsets.only(right: 30.w,top:10.w,bottom: 30.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  child: Text('详细地址',style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 32.sp,
                                  ),),
                                  padding: EdgeInsets.only(top: 20.w),
                                ),
                                SizedBox(width: 25.w,),
                                Expanded(child: TextField(
                                  controller: _controller,
                                  focusNode: _focusNode,
                                  keyboardType: TextInputType.multiline,
                                  maxLines: null,
                                  textAlign: TextAlign.right,
                                  style:  TextStyle(
                                    color: const Color(0xff666666),
                                    fontSize: 28.sp,
                                  ),
                                  decoration:  InputDecoration(
                                    contentPadding: EdgeInsets.only(left: 17.w),
                                    hintText: "街道、门牌号、小区、乡镇、村等",
                                    hintStyle: TextStyle(
                                      color: const Color(0xFFAEAEAE),
                                      fontSize: 28.sp,
                                      fontWeight: FontWeight.w500,
                                    ),
                                    counterText: "",
                                    border: const OutlineInputBorder(
                                      borderSide: BorderSide.none,
                                    ),
                                    fillColor: Colors.transparent,
                                    filled: true,
                                  ),
                                  onChanged: (value){
                                    if(entity.province==null||entity.province!.isEmpty){
                                      _controller.text = '';
                                      showToast('请选择所在地区~');
                                    }else{
                                      page=1;
                                      entity.detailAddress = value;
                                      getLocations(value);
                                    }
                                  },
                                ),),
                              ],
                            ),
                          )),
                          GestureDetector(
                            onTap: (){
                             // if(AmapTool.locationEntity.longitude!=null&&AmapTool.locationEntity.latitude!=null&&AmapTool.locationEntity.address!=null){
                             //   setState(() {
                             //     entity.latitude = AmapTool.locationEntity.latitude;
                             //     entity.longitude = AmapTool.locationEntity.longitude;
                             //     entity.province = AmapTool.locationEntity.province;
                             //     entity.city = AmapTool.locationEntity.city;
                             //     entity.region = AmapTool.locationEntity.district;
                             //     entity.detailAddress = AmapTool.locationEntity.address;
                             //     entity.adCode = AmapTool.locationEntity.adCode;
                             //     _controller.text = entity.detailAddress;
                             //   });
                             // }
                            },
                            child: Container(
                              padding: EdgeInsets.all(30.w),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Image.asset('assets/fabu/fabu_dt.png',width: 40.w,)
                                ],
                              ),
                            ),
                          ),
                          Container(
                            height: 0.5,
                            color: Color(0xffE9E8E9),
                          )
                        ],
                      ),
                    ),
                    Visibility(
                      visible: _focusNode.hasFocus && searchAddressList.isNotEmpty,
                      child: Container(
                        height: 400.w,
                        padding: EdgeInsets.all(20.w),
                        margin: EdgeInsets.only(right: 20.w),
                        decoration: BoxDecoration(
                            border: Border.all(color: defaultBarColor,width: 1),
                            borderRadius: BorderRadius.circular(10.w),
                            color: Colors.white
                        ),
                        child: EasyRefresh(
                          header: myRefreshHeader(),
                          footer: myRefreshFooter(),
                          onRefresh: ()async{
                            page = 1;
                            getLocations(entity.detailAddress!);
                          },
                          onLoad: ()async{
                            page++;
                            getLocations(entity.detailAddress!);
                          },
                          child: ListView.builder(itemBuilder: (context,index){
                            return buildAddressItem(searchAddressList[index]);
                          },itemCount: searchAddressList.length,),
                        ),
                      ),),
                    Container(
                      height: 120.w,
                      child: Column(
                        children: [
                          Expanded(child: Container(
                            padding: EdgeInsets.only(right: 30.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Text('设为默认经营地址',style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 32.sp,
                                ),),
                                Expanded(child: Container()),
                                FlutterSwitch(
                                  width: 100.w,
                                  height: 60.w,
                                  value: entity.isDefault=='1',
                                  activeColor:Color(0xff07C160),
                                  borderRadius: 30.0,
                                  onToggle: (value) {
                                    FocusScope.of(context).requestFocus(FocusNode());
                                    setState(() {
                                      entity.isDefault  = value==true?'1':'0';
                                    });
                                  },
                                )
                              ],
                            ),
                          )),
                          Container(
                            height: 0.5,
                            color: Color(0xffE9E8E9),
                          )
                        ],
                      ),
                    ),
                    Expanded(child: Container(color: Colors.transparent,)),
                  ],
                ),
              )),
              Container(
                margin: EdgeInsets.symmetric(vertical: 50.w),
                child: GestureDetector(
                  onTap: ()async{
                    FocusScope.of(context).requestFocus(FocusNode());
                    if(entity.province==null||entity.province!.isEmpty){
                      showToast('请选择所在地区~');
                      return;
                    }
                    if(entity.detailAddress==null||entity.detailAddress!.isEmpty){
                      showToast('请输入详细地址~');
                      return;
                    }
                    if(entity.latitude==null||entity.latitude!.isEmpty){
                      page = 1;
                      await getLocations('汽车站',isDone: true);
                    }
                    saveAdress();
                  },
                  child: Container(
                    height: 100.w,
                    width: 600.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: defaultBarColor,
                        borderRadius: BorderRadius.circular(10.w)
                    ),
                    child: Text('保存',style: TextStyle(
                        color: Colors.white,
                        fontSize: 36.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  saveAdress()async{

    ResponseData res;
    if(entity.id!=null){
      res = await UserAPI.updateMyJYaddress(entity.toJson());
    }else{
      res = await UserAPI.saveMyJYaddress(entity.toJson());
    }
    if(res.code==200){
      Navigator.of(context).pop();
    }
  }

  /// 输入内容检索
  getLocations(String keywords,{bool isDone = false}) async {
    Response res = await Dio().get(
      'https://restapi.amap.com/v3/place/text?keywords=$keywords&city=${entity.adCode}&citylimit=true&offset=20&page=$page&key=df9eba155edb125fc2c4e3a6a91ac4df&extensions=all',
    );
    print('检索结果====' + res.data.toString());
    if (res.data['pois'] != null && res.data['pois'].length >= 0) {
      if(page==1){
        searchAddressList = [];
      }
      // 默认地图显示第一个搜索结果
      setState(() {
        searchAddressList.addAll(res.data['pois']??[]);
       if(searchAddressList.isNotEmpty&&isDone){
         entity.currentAddressId = searchAddressList.first['id'];
         // pName = searchAddressList.first['pname'];
         // cName = searchAddressList.first['cityname'];
         // dName = searchAddressList.first['adname'];
         entity.detailAddress = searchAddressList.first['name'];
         entity.latitude = searchAddressList.first['location'].split(',')[1];
         entity.longitude = searchAddressList.first['location'].split(',').first;
       }
      });
    }
  }

  /// 构建地址检索结果
  Widget buildAddressItem(Map address) {
    return GestureDetector(
      onTap: () {
        setState(() {
          entity.currentAddressId = address['id'];
          // zoneCode = address['adcode'];
          // pName = address['pname'];
          // cName = address['cityname'];
          // dName = address['adname'];
          entity.detailAddress = address['name'];
          _controller.text = entity.detailAddress!;
          entity.latitude = searchAddressList.first['location'].split(',')[1];
          entity.longitude = searchAddressList.first['location'].split(',').first;
          FocusScope.of(context).requestFocus(FocusNode());
        });

      },
      child: Container(
        width: 1.sw,
        padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 20.w),
        color: Colors.white,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '${address['name']}',
                    style: TextStyle(
                      fontSize: 28.sp,
                      color: Color(0xFF333333),
                      fontWeight: FontWeight.bold,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  SizedBox(height: 10.w),
                  Text(
                    '${(address['district'] == null || address['district'].length == 0) ? '' : address['district']}${address['address'].length == 0 ? '' : address['address']}',
                    style: TextStyle(
                      fontSize: 22.sp,
                      color: Color(0xFF999999),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: 50.w,
              margin: EdgeInsets.only(left: 20.w, right: 10.w),
              child: Visibility(
                visible: entity.currentAddressId == address['id'],
                child: Image.asset(
                  'assets/map/select_address.png',
                  height: 48.w,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
